﻿using BasicData.API.Read.Applications.Commands;
using BasicData.API.Read.Dtos;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infrastrueturc.Interfaces;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace BasicData.API.Read.Applications.CommandHandlers
{
    /// <summary>
    /// 登录处理命令
    /// </summary>
    public class LoginQueryCommandHandlers : IRequestHandler<LoginQueryCommand, APIResult<UserDTO>>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IBaseReposiotry<User> userReposiotry;
        /// <summary>
        /// 角色仓储
        /// </summary>
        private readonly IBaseReposiotry<Role> roleReposiotry;
        /// <summary>
        /// 角色用户
        /// </summary>
        private readonly IBaseReposiotry<RoleUser> roleuserReposiotry;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userReposiotry">用户仓储</param>
        /// <param name="roleReposiotry">角色仓储</param>
        /// <param name="roleuserReposiotry">角色用户</param>

        public LoginQueryCommandHandlers(IBaseReposiotry<User> userReposiotry,IBaseReposiotry<Role> roleReposiotry,
           IBaseReposiotry<RoleUser> roleuserReposiotry)
        {
            this.userReposiotry = userReposiotry;
            this.roleReposiotry = roleReposiotry;
            this.roleuserReposiotry = roleuserReposiotry;
        }

        /// <summary>
        /// 登录查询命令处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">选择</param>
        /// <returns>返回结果</returns>
        public Task<APIResult<UserDTO>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result = new APIResult<UserDTO>();
            result.Code = ResultCode.登录成功;
            result.Message = ResultCode.登录成功.ToString();
            request.UserPass = request.UserPass.GetMD5().ToUpper();
            var list = from a in userReposiotry.GetAll()
                       join b in roleuserReposiotry.GetAll() on a.UserId equals b.UserId
                       join c in roleReposiotry.GetAll() on b.RoleId equals c.RoleId
                       where a.UserName == request.UserName && a.UserPass == request.UserPass
                       select new UserDTO
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserPass = a.UserPass,
                           UserNickname = a.UserNickname,
                           RoleId = c.RoleId,
                           RoleName = c.RoleName
                       };
            var query = list.FirstOrDefault();
            if (query==null)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString()+"用户名密码不匹配";
                return Task.FromResult(result);
            }
            query.Token = CreateTokenString( query );
            result.Data= query;               
            return Task.FromResult(result);
        }
        private string CreateTokenString(UserDTO dTO)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var claims = new[]
            {
                 new Claim("UserId",dTO.UserId.ToString()),
                 new Claim("UserNickname",dTO.UserNickname.ToString()),
                 new Claim("RoleId",dTO.RoleId.ToString())
             };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                claims:claims,
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
